package week2;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author The Setting sun
 * @create 2021-09-15 10:29
 */
public class BMI {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setLayout(new GridLayout(2, 1, 10, 10));

        JPanel p1 = new JPanel();
        JLabel l1 = new JLabel(new ImageIcon("BMI.png"));
        p1.add(l1);

        JPanel all = new JPanel(new GridLayout(4, 1));

        JPanel p2 = new JPanel(new FlowLayout());
        JLabel label1 = new JLabel("身高（cm）");
        label1.setFont(new Font("微软雅黑", Font.BOLD, 16));
        JTextField textField1 = new JTextField(10);
        p2.add(label1);
        p2.add(textField1);

        JPanel p3 = new JPanel(new FlowLayout());
        JLabel label2 = new JLabel("体重（kg）");
        label2.setFont(new Font("微软雅黑", Font.BOLD, 16));
        JTextField textField2 = new JTextField(10);
        p3.add(label2);
        p3.add(textField2);

        JPanel p4 = new JPanel(new FlowLayout());
        JLabel label3 = new JLabel("你的BMI");
        label3.setFont(new Font("微软雅黑", Font.BOLD, 16));
        JTextField textField3 = new JTextField(10);
        JButton button = new JButton("计算");

        JPanel p5 = new JPanel();
        JLabel label = new JLabel();
        label.setFont(new Font("微软雅黑", Font.BOLD, 16));
        p5.add(label);

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text1 = textField1.getText();
                Double h = new Double(text1);

                String text2 = textField2.getText();
                Double w = new Double(text2);

                double value = w / ((h / 100) * (h / 100));
                String bmi = String.format("%.4f", value);
                textField3.setText(bmi);

                if (value >= 24) {
                    label.setText("你的体重偏重，需要减肥");
                } else if (value <= 18.4) {
                    label.setText("你的体重偏轻，需要增肥");
                } else {
                    label.setText("你的体重正常，保持现状");
                }
            }
        });
        p4.add(label3);
        p4.add(textField3);
        p4.add(button);

        all.add(p2);
        all.add(p3);
        all.add(p4);
        all.add(p5);

        frame.add(p1);
        frame.add(all);

        frame.setSize(700, 600);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
